package ar.edu.unlu.sistemas.p2p.business.util;

import java.io.FileInputStream;
import java.io.IOException;

public class ByteHelper {

	private static final String HEXES = "0123456789ABCDEF";

	/**
	 * Convierte un entero mayor igual a cero en un array de bytes
	 * 
	 * @param num número entero positivo a convertir
	 * @param arr arreglo de bytes donde almacenar
	 * @param index posicion del arreglo
	 */
	public static void intNumIntoByteArr(int num, byte[] arr, int index) {
		arr[index] = (byte)( (num << 16) >> 24 );
		arr[index+1] =(byte)( (num << 24) >> 24 );
	}

	/**
	 * Convierte un long mayor igual a cero en un array de bytes
	 * 
	 * @param num número long positivo a convertir
	 * @param arr arreglo de bytes donde almacenar
	 * @param index posicion del arreglo
	 */
	public static void longNumIntoByteArr(long num, byte[] arr, int index) {
		arr[index] =(byte)( (num << 24) >> 48 );
		arr[index+1] =(byte)( (num << 32) >> 48 );
		arr[index+2] =(byte)( (num << 40) >> 48 );
		arr[index+3] =(byte)( (num << 48) >> 48 );
	}


	/**
	 * Convierte un array de bytes en un string que lo representa en Hexadecimal
	 * 
	 * @param raw
	 * @return
	 */
	public static String getHex( byte [] raw ) {
		if ( raw == null ) {
			return null;
		}
		final StringBuilder hex = new StringBuilder( 2 * raw.length );
		for ( final byte b : raw ) {
			hex.append(HEXES.charAt((b & 0xF0) >> 4))
			.append(HEXES.charAt((b & 0x0F)));
		}
		return hex.toString();
	}

	
	public static String readTextFile(FileInputStream fis, String encoding) throws IOException {
		int bufferSize = fis.available();
		int readed;
		byte[] buffer = new byte[bufferSize];
		StringBuffer sb = new StringBuffer();
		while ((readed = fis.read(buffer)) != -1) {
			if (readed != bufferSize) {
				byte[] tempBuffer = new byte[readed];
				for (int i=0;i<readed;i++) {
					tempBuffer[i] = buffer[i];
				}
				sb.append(new String(tempBuffer,encoding));
			} else {
				sb.append(new String(buffer,encoding));
			}
		}
		fis.close();
		return sb.toString();
	}

}
